* Generate Figures 3, 5 (right panel), A.2, and Table 2

* Locals: `1' is `outputfolder', `2' is `GraphsByEpi', `3' is `windowstart', and
* `4' is `windowend'

sort ccode episode year
drop _merge
merge m:1 ccode episode using "temp/vars_for_PVSQ.dta" // Bring avgXgrowth avgMgrowth used in F5_B.pdf
drop _merge

* Define growth in relative quantity
gen relQrer = ((relMIMD2/100+1) * (relrer/100+1) - 1)*100

* create normyear dummies & interaction variables
foreach t of num 0/8 {
gen dum`t'=0
replace dum`t'=1 if normyear==`t'
gen interRERe`t' = dum`t' * relrer //
}

* Create episode dummies & corresponding interaction variables
* Tags for devaluation episodes in scatter plot
gen devaluationYear2 = devaluationYear
tostring devaluationYear2, replace
gen epiname = ccode + devaluationYear2
gen ccode_2digit = substr(ccode,1,2)
gen devaluationYear_2digit = substr(devaluationYear2,3,2)
gen epiname_short = ccode_2digit + devaluationYear_2digit

drop dum*
local r=0
levelsof epiname, local(EpiList)
foreach n of local EpiList {
local r = `r'+1
capture gen dum`r'=0
capture replace dum`r'=1 if epiname=="`n'"
capture gen interRERCe`r' = dum`r' * relrer
label var interRERCe`r' "`n'"
}

* Create normyear dummies: pre4 is a dummy for normyear=-4; post0 is dummy for normyear=0
foreach t of num `3'/-2{ // omit -1 which is normalized in regressions below
local t2=-1 * `t'
gen PRE`t2' =0
replace PRE`t2' =1 if normyear==`t'	
}
foreach t of num 0/`4'{	
gen POST`t' =0
replace POST`t' =1 if normyear==`t'	
}

* Generate figures
set graphics on
preserve
	collapse (mean) relrer relrer_cpi relMIMD2 relQrer, by(normyear)
	save "temp/PVSQ_means.dta", replace
restore
preserve
	collapse (semean) relrer relrer_cpi relMIMD2 relQrer, by(normyear) 
	foreach var in relrer relrer_cpi relMIMD2 relQrer {
	ren `var' `var'_se
	}	
	save "temp/PVSQ_se.dta", replace	
restore
preserve
	use "temp/F2_means.dta",clear
	keep normyear relimportshare relimportshare2 relrer
	ren relrer relrerF2
	sort normyear
	save "temp/F2_means_forPVSQ.dta",replace
restore
preserve
	use "temp/PVSQ_means.dta",clear
	merge 1:1 normyear using "temp/PVSQ_se.dta"
	gen up = relQrer + relQrer_se
	gen down = relQrer - relQrer_se
	gen up_rer = relrer + relrer_se
	gen down_rer = relrer - relrer_se
	drop _merge
	merge 1:1 normyear using "temp/F2_means_forPVSQ.dta"
	drop _merge
	* Figure 3 (left panel)
	graph set window fontface "Times"
	tw (line relQrer normyear, lc(blue) lw(thick)) ///
	   (line up normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line down normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	   (scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	   (line up_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	   (line relimportshare2 normyear, lc(blue) lw(0)) /// invisible import share to make yscale comparable to Figure 2
	   , yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percentage Change") /// 
	   graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) ///
	   legend(off) scale(1.2) ///
	   text(-15 -1  "RER", color(red) size(small)) /// 
	   text(-4 2 "Rel. Import Quantity", color(blue) size(small)) /// 
	   xlab(`3'(1)`4') title("{bf:Rel. Import Quantity Index}", color(black))
	  graph export "`1'/F3_A.pdf", replace
restore

* Regressions for Table 2
xi: quietly regress relMIMD2 relrer, r  
estimates store One
xi: quietly regress relMIMD2 relrer i.epi, r  
estimates store Two
xi: quietly regress relMIMD2 relrer i.epi i.normyear, r 
estimates store TwoB
if 1==0{ // run these lines to generate Table 2 with the CPI-based RER
xi: quietly regress relMIMD2 relrer_cpi, r  
estimates store One_cpi
xi: quietly regress relMIMD2 relrer_cpi i.epi, r  
estimates store Two_cpi
xi: quietly regress relMIMD2 relrer_cpi i.epi i.normyear, r  
estimates store TwoB_cpi
}
xi: quietly regress relMIMD2 interRERe* i.epi i.normyear,r  // Note: this needs to be the last regression because SigmaGraph.do will use the coeffs on interactions
estimates store Three
// Coefficients multiplied by -1 to reflect how relative import spending reacts to devaluation (decrease in RER)
esttab One Two TwoB Three using "`1'/Table2.csv", transform(-@) keep(relrer interRERe*) b(%9.2f) se stats(r2 N) star(* 0.1 ** 0.05 *** 0.01) replace
// Confidence interval:
esttab One Two TwoB Three using "`1'/Table2_ci.csv", transform(-@) keep(relrer interRERe*) b(%9.2f) ci stats(r2 N) star(* 0.1 ** 0.05 *** 0.01) replace	
local graphname "F3_B"
qui do "Analysis_dofiles/SigmaGraph.do" `1' `3' `4' `graphname'

if 1==0{// run these lines to generate Table 2 with the CPI-based RER
* Redefine the interaction terms interRERe using CPI RER
drop interRERe*
drop dum*
foreach t of num 0/8 {
gen dum`t'=0
replace dum`t'=1 if normyear==`t'
gen interRERe`t' = dum`t' * relrer_cpi
}
* Re-run reg with interactions:
xi: quietly regress relMIMD2 interRERe* i.epi i.normyear,r  
estimates store Three_cpi
* Re do the graph:
local graphname "F3_B_CPI"
qui do "Analysis_dofiles/SigmaGraph.do" `1' `3' `4' `graphname'
esttab One_cpi Two_cpi TwoB_cpi Three_cpi using "`1'/Table2_CPI.csv", transform(-@) keep(relrer_cpi interRERe*) b(%9.2f) se stats(r2 N) star(* 0.1 ** 0.05 *** 0.01) replace	
esttab One_cpi Two_cpi TwoB_cpi Three_cpi using "`1'/Table2_ci_CPI.csv", transform(-@) keep(relrer_cpi interRERe*) b(%9.2f) ci stats(r2 N) star(* 0.1 ** 0.05 *** 0.01) replace	
}

* Episode-specific elasticities	
preserve
	use "temp/vars_for_PVSQ.dta", clear
	sort ccode devaluationYear
	save "temp/vars_for_PVSQ_2.dta", replace
restore
xi: quietly regress relMIMD2 interRERCe* i.epi i.normyear,r
estimates store One
gen epsiRS_exact=.
gen event=""
local r=0
levelsof epiname_short, local(EpiList)
foreach n of local EpiList {
		local r = `r'+1			
		replace epsiRS_exact = -_b[interRERCe`r'] if _n == `r'
		replace event= "`n'" if _n == `r' 
}
gen event_long=""
local rl=0
levelsof epiname, local(EpiList_long)
foreach n of local EpiList_long {
		local rl = `rl'+1
		replace event_long= "`n'" if _n == `rl' 
}
		
* Export elasticity 			
xi: quietly regress relSXSD interRERCe* i.epi i.normyear,r
estimates store OneX
gen epsiX_exact=.
local rx=0
foreach n of local EpiList {
		local rx = `rx'+1
		replace epsiX_exact = - _b[interRERCe`rx'] if _n == `rx' // relative foreign sales elasticity
}		
preserve
	keep if _n<=`r'
	keep  event event_long epsiRS_exact epsiX_exact
	gen devaluationYear= substr(event_long,4,8)
	destring devaluationYear, replace
	gen ccode= substr(event_long,1,3)
	sort ccode devaluationYear
	merge 1:1 ccode devaluationYear using "temp/vars_for_PVSQ_2.dta" 
	twoway (scatter avgMgrowth avgXgrowth if avgXgrowth<200  , mlabel(event) xscale(range(-5 110))), graphregion(color(white)) graphregion(margin(l=0 r=0 b=0 t=0)) ///
			xtitle(Export Share Growth (%)) ytitle(Imported Input Share Growth (%))
	graph export "`1'/F5_B.pdf", replace
	twoway (scatter epsiRS_exact epsiX_exact if epsiX_exact<4, mlabel(event)), graphregion(color(white)) graphregion(margin(l=0 r=2.5 b=0 t=0)) ///  
			xtitle(Elasticity of Rel. Export Revenue) ytitle(Elasticity of Rel. Import Spending)
	graph export "`1'/FA2.pdf", replace 
restore
